package io.lckgroup.modules.lck.controller.wxgzh;

import io.lckgroup.common.utils.R;
import io.lckgroup.modules.lck.entity.CustomerInfoEntity;
import io.lckgroup.modules.lck.service.CustomerInfoService;
import io.lckgroup.modules.lck.utils.JwtUtils;
import io.lckgroup.modules.lck.utils.WxUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信公众号网页授权
 *
 * @author tw
 */
@RestController
@RequestMapping("/mp/wxOauth")
public class WeiXinOauth {

    @Autowired
    private CustomerInfoService customerInfoService;
    @Autowired
    private JwtUtils jwtUtils;

    @RequestMapping("/login/{code}")
    public R getUserInfo(@PathVariable String code) {
        Map map = new HashMap();
        //使用code获取用户信息,并封装为 CustomerInfoEntity
        CustomerInfoEntity customer = WxUtils.userInfo(code);
        //根据openid查询用户信息
        CustomerInfoEntity customerInfoEntity = customerInfoService.getCustomerByOpenid(customer.getOpenId());
        if (customerInfoEntity == null) {
            customerInfoEntity = customerInfoService.saveAndSelectCustomer(customer);
        }
        String token = jwtUtils.generateToken(customerInfoEntity.getId());
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        map.put("user", customer);
        return R.ok().put("data", map);
    }
}
